package com.sanjin.configuration.security;

import com.alibaba.fastjson.JSON;
import com.sanjin.enums.ResponseEnum;
import com.sanjin.utils.ResponseVoUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @description: 权限不足异常处理类
 * @author: sanjin
 * @date: 2019/5/6 9:22
 */
@Slf4j
public class AuthorizationAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //登陆状态下，权限不足执行该方法
        log.info("权限不足：" + accessDeniedException.getMessage());
        response.setStatus(200);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        String body = JSON.toJSONString(ResponseVoUtils.error(ResponseEnum.AUTHORIZATEERROR));
        printWriter.write(body);
        printWriter.flush();
    }
}
